<template>
  <div class="container">
    <el-table
      ref="scrollTable"
      v-loading="loading"
      v-bind="setAttrs(tableAttr)"
      :data="tableData"
      @row-click="rowClick"
      @sort-change="sortChange"
      @selection-change="selectionChange"
      @cell-mouse-enter="handleMouse"
      @cell-mouse-leave="handleMouseLeve"
    >
      <!-- <el-table v-loading="loading" v-el-height-adaptive-table="{bottomOffset, adaptive}" :data="tableData" :height="adaptive?height:''" style="width: 100%" @selection-change="selectionChange"> -->
      <el-table-column
        v-if="selectVisible"
        type="selection"
        width="45"
        align="left"
        :selectable="selectable"
      />
      <template v-for="column in columns">
        <el-table-column
          v-if="column.slots"
          :key="column.prop"
          v-bind="setAttrs(column)"
        >
          <template slot-scope="scope">
            <Render
              :custom-data="column.slots"
              :class="column.class"
              :row="scope.row"
              :index="scope.$index"
            />
          </template>
        </el-table-column>
        <el-table-column v-else :key="column.prop" v-bind="setAttrs(column)" />
      </template>
    </el-table>
    <!--分页栏-->
    <!-- 分页 -->
    <Pagination
      :total="total"
      :hidden="hidden"
      :page="pageOpt.pageNum"
      :limit="pageOpt.pageSize"
      :page-sizes="pageSizes"
      :auto-scroll="isScrollTop"
      @pagination="pagination"
    />
  </div>
</template>
<script>
import Render from './render'
// import { scrollTo } from '@/utils/scroll-to'
import Pagination from '@/components/Pagination'
import request from '@/utils/request'
// import { parseTime } from '@/utils'
import tableScroll from '@/mixins/tableScroll'
export default {
  name: 'SrmTable',
  components: {
    Render,
    Pagination
    // ImagePreview
  },
  mixins: [tableScroll],
  props: {
    selectable: {
      type: Function,
      default: () => {}
    },
    contentType: {
      type: String,
      default: 'application/json'
    },
    // 外部传入的table数据源 不走组件内接口
    sourceData: {
      type: Array,
      default: () => []
    },
    // 控制分页组件的显示隐藏
    hidden: {
      type: Boolean,
      default: false
    },
    isLoad: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => []
    },
    // 是否加载中
    sourceDataLoading: {
      type: Boolean,
      default: false
    },
    // 是否可选择行
    selectVisible: {
      type: Boolean,
      default: false
    },
    // 分页查询数据
    pageRequest: {
      type: Object,
      default: () => ({
        pageNum: 1,
        pageSize: 20
      })
    },
    // 每页条数选择器
    pageSizes: {
      type: Array,
      default: () => [10, 20, 50, 100]
    },
    // table组件的属性设置
    tableAttr: {
      type: Object,
      default: () => ({
        border: false
      })
    },
    // 是否开启table自适应高度 默认关闭
    adaptive: {
      type: Boolean,
      default: false
    },
    // table自适应高度距离底部的高度 开启自适应模式时生效
    bottomOffset: {
      type: Number,
      default: 80
    },
    // table高度 默认100% 开启自适应高度时必须设置高度 不设置高度自适应无效
    height: {
      type: String,
      default: '100%'
    },
    // 后端接口api地址 和请求方式  post|/v2/supplier/order/queryOrderList
    url: {
      type: String,
      default: ''
    },
    // 筛选条件
    params: {
      type: Object,
      default: () => ({})
    },
    // 列表数据总数
    listTotal: {
      type: Number,
      default: 0
    },
    isScrollTop: {
      type: Boolean,
      default: true
    }
  },
  provide() {
    return {
      vm: this
    }
  },
  data() {
    return {
      loading: false,
      downloadLoading: false,
      // 当前选择项的集合
      selections: [],
      // sourceData: [],
      tableData: [],
      total: 10,
      pageOpt: this.pageRequest,
      selfLoading: true
    }
  },
  computed: {
    layout() {
      const layout = ['total', 'prev', 'pager', 'next']
      if (this.pageSizes.length) {
        layout.push('sizes')
      }
      return layout.join(', ')
    },
    // 是否是外部数据源 外部注入的数据源不走内部接口逻辑
    isExternal() {
      const { sourceData = [] } = this
      return sourceData.length
    }
  },
  watch: {
    // 外部传入的列表数据 需要传入分页的总条数
    sourceData: {
      handler(list) {
        this.tableData = list
        setTimeout(() => {
          this.$emit('update:sourceDataLoading', false)
        }, 500)
      },
      immediate: true
    },
    // 外部数据注入时的loading
    sourceDataLoading: {
      handler(loading) {
        this.loading = loading
      },
      immediate: true
    },
    // 外部传入的列表数据 需要传入分页的总条数
    listTotal: {
      handler(total) {
        this.total = total
      },
      immediate: true
    },
    // 筛选条件变化触发接口调用 更新列表数据
    params(params) {
      const { request = false } = params
      if (request) {
        this.pageOpt.pageNum = 1
        this.initTable()
      }
      params['request'] = false
      this.$emit('update:params', params)
    },
    // table结构变化 重新渲染
    columns() {
      this.$nextTick(() => {
        this.$refs.scrollTable.doLayout()
      })
    }
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.scrollTable.doLayout()
    })
  },
  mounted() {
    // 有外部数据源注入时不走内部接口
    const { isExternal, isLoad } = this
    isLoad && !isExternal && this.initTable()
  },
  methods: {
    resetParams() {
      let _params = this.params
      let _curKey = {}
      Object.keys(_params).forEach(itemKey => {
        if (itemKey.match(/[:|,]/g)) {
          const [curType, curFiled] = itemKey.split(':')
          if (curType === 'picker') {
            // eslint-disable-next-line no-undef
            _curKey = _.omit(_params, [itemKey]) // 删除params中的时间属性
            console.log('curKey', _curKey)
            const [v1, v2] = _params[itemKey] || [null, null]
            const [k1, k2] = curFiled.split(',')
            _params = {
              ..._curKey,
              [k1]: v1 ? new Date(v1).getTime() : null,
              [k2]: v2 ? new Date(v2).getTime() : null
            }
          }
        }
      })
      return _params
    },
    async initTable(v) {
      this.loading = true
      const realParams = this.resetParams()
      const reqOpt = this.url.split('|')
      const [method, url] = reqOpt[1] ? reqOpt : ['post', reqOpt[0]]

      const reqKey = reqOpt[2]
        ? reqOpt[2]
        : method.toLowerCase() === 'post'
          ? 'data'
          : 'params'
      try {
        const { list = [], total = 0 } = await request({
          url,
          method,
          [reqKey]: {
            ...this.pageOpt,
            ...realParams
          },
          headers: {
            'Content-Type': this.contentType
          }
        })
        setTimeout(() => {
          this.loading = false
          this.tableData = list
          this.total = total
          this.$emit('getTotal', total)
        }, 500)
      } catch (e) {
        this.loading = false
      }
    },
    // 已选项 多选
    selectionChange(selections) {
      this.selections = selections
      this.$emit('selectionChange', { selections })
    },
    // 排序
    sortChange(v) {
      this.$emit('sort-change', v)
    },
    // 单行点击
    rowClick(row, column, event) {
      this.$emit('row-click', row)
    },
    // 鼠标移入
    handleMouse(row) {
      this.$emit('cell-mouse-enter', row)
    },
    // 鼠标移出
    handleMouseLeve(row) {
      this.$emit('cell-mouse-leave', row)
    },
    // select
    // selectable(row) {
    //   // console.log('row',)
    //   this.$nextTick(() => {
    //     this.$emit('selectable', row)
    //   })
    // },
    setAttrs(params) {
      // eslint-disable-next-line
      const { ...options } = params
      if (!options.align) {
        options.align = 'left'
      }
      return { ...options }
    },
    // 分页
    pagination(ev) {
      // 有外部数据源注入时不走内部分页
      const { isExternal } = this
      const { page, limit } = ev
      this.pageOpt.pageNum = page
      this.pageOpt.pageSize = limit
      if (isExternal) {
        this.$emit('update:pageRequest', this.pageOpt)
        this.$emit('pagination', ev)
      } else {
        this.initTable()
      }
      this.$refs.scrollTable.bodyWrapper.scrollTop = 0
      // scrollTo(0, 800)
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  margin: 0 0 25px 0;
}
.srm-table_img {
  cursor: pointer;
}
.toolbar {
  margin-top: 15px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .handle-wrap {
    position: absolute;
    left: 0;
  }
}
.handle-wrap {
  display: flex;
  align-items: center;
  text-align: center;
  margin-bottom: 15px;
}
* + .table-export_btn {
  margin-left: 15px;
}
</style>
